import config from '../config'
import axios from 'axios'

function fetch(url, success, error) {
  axios.get(url)
    .then(response => {
      const result = response.data
      if (parseInt(result.code) === 0) {
        success && success(result.data)
      } else {
        console.error(`error: ${result.code} - ${result.message}`)
        error && error(result.message)
      }
    })
    .catch(error)
}

function toKebabCase(value) {
  return value.split('')
    .map(letter => letter.toLowerCase() === letter ? letter : `-${letter.toLowerCase()}`)
    .join('')
}

export function fetchEndpoint(endpoint, params) {
  let url = `${config.api}/v1/${toKebabCase(endpoint)}`
  if (params) {
    let queryString = Object.keys(params)
      .filter(key => !!params[key])
      .map(key => `${key}=${params[key]}`)
      .join('&')
    url = queryString ? `${url}?${queryString}` : url
  }

  return new Promise((resolve, reject) => {
    fetch(url, resolve, reject)
  })
}

export function fetchPageConfig(page) {
  page = page === 'activity' ? 'activity_list' : page
  const url = `${config.api}/v1/web-pages/${page}`
  return new Promise((resolve, reject) => {
    fetch(url, resolve, reject)
  })
}
